<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-button size="mini" class="no_use" style="color: #fff">可预约</el-button>
        <el-button size="mini" class="used" style="color: #fff">已预约</el-button>
        <el-button size="mini" class="locked" style="color: #fff">被锁定</el-button>
      </el-col>
      <el-col :span="10">
        <el-row>
          <el-col :span="12" :offset="6">
            <el-button-group>
              <el-button type="primary" icon="el-icon-arrow-left" @click="startDate = startDate.add('dayofyear',-7,true)">前七天</el-button>
              <el-button type="primary" @click="startDate = startDate.add('dayofyear',7,true)">后七天<i class="el-icon-arrow-right el-icon--right"/></el-button>
            </el-button-group>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="5">
        <el-row type="flex" justify="end">
          <el-col :span="12">
            <el-select v-if="isAdminUser" v-model="shopId" placeholder="请选择门店">
              <el-option v-for="item in shopData" :key="item.shopId" :value="item.shopId" :label="item.shopName"/>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-date-picker
              v-model="startDate"
              type="date"
              placeholder="选择日期"/>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <!-- 表格list -->
    <el-row>
      <el-col :span="24" :gutter="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          :height="tableHeight"
          border
          fit
          highlight-current-row>
          <el-table-column align="center" width="80" fixed="left">
            <template slot-scope="scope">
              <div>
                <template v-if="isAdminUser">
                  <span>{{ scope.row.shopName }}</span>
                  <br>
                </template>
                <span>{{ scope.row.dayWeekStr }}</span>
                <br>
                <span>{{ scope.row.scheduleDay | dayFilter }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-for="item in columnLabel" :key="item.label" :label="item.label" show-overflow-tooltip width="150" align="center">
            <template slot-scope="scope">
              <div>
                <div v-for="detail in scope.row.groupSxScheduleDetailList[item.hour]" style="float:left;margin-left: 5px; margin-top: 5px">
                  <div v-for="item in detail.pointDetails" style="margin-left: 5px; margin-top: 5px">
                    <!--<el-tooltip content="Top center" placement="top">-->
                      <!--<div slot="content">-->
                        <!--<span>时间点: {{ detail.scheduleTime | timeFilter }}</span>-->
                        <!--<br>-->
                        <!--<span>排序: {{ item.sort + 1 }}</span>-->
                        <!--<br>-->
                        <!--<span>状态: {{ item.status | scheduleStatusFilter }}</span>-->
                      <!--</div>-->
                      <!--<div :class="['box',getScheduleStatusClass(item.status)]"/>-->
                    <!--</el-tooltip>-->
                    <!--<el-popover-->
                      <!--placement="top"-->
                      <!--width="300">-->
                      <!--<p><span>时间点: {{ detail.scheduleTime | timeFilter }}</span></p>-->
                      <!--<p><span>排序: {{ item.sort + 1 }}</span></p>-->
                      <!--<p><span>状态: {{ item.status | scheduleStatusFilter }}</span></p>-->
                      <!--<p v-if="item.status == 4"><span>订单号: {{ item.orderId }}</span></p>-->
                      <!--<div style="text-align: right; margin: 0">-->
                        <!--<el-button v-if="item.status == 4" size="mini" type="text" @click="visible2 = false"></el-button>-->
                        <!--<el-button v-else-if="item.status == 3" size="mini" type="text" @click="handleLock(detail, item, 'lock')">锁定</el-button>-->
                        <!--<el-button v-else-if="item.status == 5" size="mini" type="text" @click="handleLock(detail, item, 'unlock')">解锁</el-button>-->
                      <!--</div>-->
                      <div :class="['box',getScheduleStatusClass(item.status)]" @click="showDetail(detail, item)"/>
                    <!--</el-popover>-->
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible">
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 问题确认 -->
    <el-dialog
      :visible.sync="detailDialogVisible"
      title="详情"
      width="30%"
      >
      <p><span>时间点: {{ selectDetail.scheduleTime | timeFilter }}</span></p>
      <p><span>排序: {{ selectPoint.sort + 1 }}</span></p>
      <p><span>状态: {{ selectPoint.status | scheduleStatusFilter }}</span></p>
      <template v-if="selectPoint.status == 4">
        <p ><span>订单号: {{ selectPoint.orderId }}</span></p>
        <p ><span>套餐内容:</span><span v-for="(value , key) in orderRecord.item"> {{ value.productName }}</span></p>
        <p ><span>手机号: {{ orderRecord.phone }}</span></p>
        <p ><span>顾客姓名: {{ orderRecord.userName }}</span></p>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="selectPoint.status == 4" size="mini" @click="visible2 = false"></el-button>
        <el-button v-else-if="selectPoint.status == 3" size="mini" @click="handleLock(selectDetail, selectPoint, 'lock')">锁定</el-button>
        <el-button v-else-if="selectPoint.status == 5" size="mini" @click="handleLock(selectDetail, selectPoint, 'unlock')">解锁</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import SxScheduleDetailApi from '@/api/manage/SxScheduleDetailApi'
import SxScheduleInfoApi from '@/api/manage/SxScheduleInfoApi'
import SxShopInfoApi from '@/api/manage/SxShopInfoApi'
import SxOrderRecordApi from '@/api/manage/SxOrderRecordApi'
import waves from '@/directive/waves' // Waves directive
export default {
  directives: { waves },
  filters: {
    scheduleStatusFilter(status) {
      const statusMap = {
        1: '未使用',
        2: '已满',
        3: '可预约',
        4: '已预约',
        5: '已锁定'
      }
      return statusMap[status]
    },
    scheduleStatusClassFilter(status) {
      const statusMap = {
        1: 'no_full',
        2: 'full',
        3: 'no_use',
        4: 'used',
        5: 'locked'
      }
      return statusMap[status]
    },
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'gray',
        0: 'danger'
      }
      return statusMap[status]
    },
    validFilter(status) {
      const statusMap = {
        1: '有效',
        0: '作废'
      }
      return statusMap[status]
    },
    timeFilter(time) {
      if (time) {
        return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    },
    dayFilter(time) {
      if (time) {
        return new Date(time).Format('MM-dd')
      } else {
        return ''
      }
    }
  },
  data() {
    return {
      tableKey: 0, // 表格key值
      list: null, // 表格对象
      listLoading: true, // 表格加载框
      startDate: new Date(), // 返回
      startHour: 8,
      endHour: 22,
      shopId: '',
      shopData: [],
      total: 0, // 分页总数
      tableHeight: window.innerHeight - 120, // 表格高度
      temp: {}, // 编辑框临时变量
      statusOptions: { // 有效无效下拉框
        '1': '有效',
        '0': '作废'
      },
      dialogFormVisible: false, // 编辑框显示
      dialogStatus: '', // 编辑框更新插入状态
      textMap: { // 编辑框标题
        update: '编辑',
        create: '创建'
      },
      rules: { // 编辑框校验规则
		   sxScheduleDetailName: [{ required: true, message: '排班细表名称', trigger: 'change' }]
      },
      visible2: false,
      detailDialogVisible: false,
      selectDetail: {
        scheduleTime: ''
      },
      selectPoint: {
        sort: 1,
        status: 3,
        orderId: ''
      },
      orderRecord: {
        phone: '',
        userName: '',
        remark: ''
      }
    }
  },
  computed: {
    columnLabel() {
      const arr = []
      for (let i = this.startHour; i <= this.endHour; i++) {
        arr.push({ hour: i, label: i + ':00' })
      }
      return arr
    },
    rangeParam() {
      const param = { startTime: this.startDate.getTime(), endDays: 7 }
      let shopId = this.shopId
      if (!this.isAdminUser) {
        shopId = this.ownShopId
      }
      param['shopId'] = shopId
      return param
    },
    ownShopId() {
      return this.$store.getters.manageShop
    },
    isAdminUser() {
      if (this.ownShopId === '' || this.ownShopId === '1') {
        return true
      }
      return false
    },
    validSwitch: {
      // getter
      get: function() {
        return this.temp.validFlag === '1'
      },
      // setter
      set: function(newValue) {
        if (newValue) {
          this.temp.validFlag = '1'
        } else {
          this.temp.validFlag = '0'
        }
      }
    }
  },
  watch: {
    startDate(newVal, oldVal) {
      debugger
      this.fetchData()
    },
    shopId(newVal, oldVal) {
      this.findScheduleRange()
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    getDetails(row, item) {
    },
    /**
     * 获取表格数据
     */
    fetchData() {
      debugger
      const that = this
      this.listLoading = true
      if (this.isAdminUser) {
        this.getShopData()
      } else {
        this.findScheduleRange()
      }
    },

    findScheduleRange() {
      const that = this
      SxScheduleInfoApi.findScheduleRange(this.rangeParam).then((data) => {
        if (data) {
          for (const item of data) {
            item.startHour = parseInt(new Date(item.startTime).getHours())
            item.endHour = parseInt(new Date(item.endTime).getHours())
            if (item.sxScheduleDetailList) {
              item.groupSxScheduleDetailList = this.$_.groupBy(item.sxScheduleDetailList, 'scheduleHour')
            } else {
              item.groupSxScheduleDetailList = {}
            }
          }
          if (data.length > 0) {
            this.startHour = this.$_.minBy(data, (o) => o.startHour).startHour
            this.endHour = this.$_.maxBy(data, (o) => o.endHour).endHour
          }
        }
        that.list = data
        that.listLoading = false
      })
    },

    /**
     * 获取门店地址
     * */
    getShopData() {
      SxShopInfoApi.getList({}).then(data => {
        this.shopData = data
        if (this.shopData && this.shopData.length > 0) {
          this.shopId = this.shopData[0].shopId
        }
        this.findScheduleRange()
      })
    },
    /**
       * 新增弹窗
       */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
       * 清空弹窗内容
       */
    resetTemp() {
      this.temp = {
        scheduleId: '',
        subNo: '',
        scheduleTime: '',
        createdTime: '',
        modifiedTime: '',
        validFlag: '1'
      }
    },
    /**
       * 确定新增
       */
    createData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          SxScheduleDetailApi.insert(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.findScheduleRange()
              }
            })
          })
        }
      })
    },
    /**
       * 编辑弹窗
       */
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
       * 确认编辑
       */
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          SxScheduleDetailApi.update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.findScheduleRange()
              }
            })
          })
        }
      })
    },
    /**
       * 删除操作
       */
    handleDelete(row) {
      const that = this
      SxScheduleDetailApi.remove({ scheduleId: row.scheduleId }).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 1000,
          onClose() {
            that.findScheduleRange()
          }
        })
      })
    },
    /**
       * 搜索过滤
       */
    handleFilter() {
      this.listQuery.pageNum = 1
      this.findScheduleRange()
    },
    getScheduleStatusClass(status) {
      const statusMap = {
        1: 'no_full',
        2: 'full',
        3: 'no_use',
        4: 'used',
        5: 'locked'
      }
      return statusMap[status]
    },
    handleLock(detail, item, handle) {
      debugger
      let param = { subNo: item.subNo, id: item.id, handle: handle }
      SxScheduleDetailApi.lockScheduleDetail(param).then(data => {
        if (handle === 'lock') {
          item.status = 5
        } else {
          item.status = 3
        }
      })
    },
    showDetail(detail, item) {
      this.selectDetail = detail
      this.selectPoint = item
      if (this.selectPoint.status == 4 && this.selectPoint.orderId) {
        SxOrderRecordApi.findList({ orderId: this.selectPoint.orderId }).then((data) => {
          if (data && data.length > 0) {
            this.orderRecord = data[0]
          }
          this.detailDialogVisible = true
        })
      } else {
        this.detailDialogVisible = true
      }
    }
  }
}
</script>

<style scoped>
  .box {
    width: 20px;
    height: 20px;
  }
  .full {
    background-color: #3c763d;
  }
  .no_full {
    background-color: #9E9E9E;
  }
  .no_use {
    background-color: #13b5b1;
  }
  .used {
    background-color: #8a6d3b;
  }
  .locked {
    background-color: #aaaaaa;
  }
</style>
